<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="addRoleDialog = true">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色信息表格内容 -->
      <el-table :data="roelsForm" border stripe style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, t1) in scope.row.children"
              :key="item1.id"
              :class="[t1 === 0 ? 'el-row-top' : '', 'el-row-bottom', 'vcenter']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag
                  type="primary"
                  closable
                  @close="removeRightsClose(scope.row, item1.id)"
                >{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, t2) in item1.children"
                  :key="item2.id"
                  :class="[t2 === 0 ? '' : 'el-row-top', 'vcenter']"
                >
                  <!-- 渲染二级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightsClose(scope.row, item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-row
                      v-for="(item3, t3) in item2.children"
                      :key="item3.id"
                      :class="t3 === 0 ? '' : 'el-row-top'"
                    >
                      <el-col :span="24">
                        <el-tag
                          type="warning"
                          closable
                          @close="removeRightsClose(scope.row, item3.id)"
                        >{{item3.authName}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <!-- 操作按钮 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setRightsShow(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleDialog" width="40%">
      <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleRef" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addRoleForm.roleDesc" prop="roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addRoleDialogCancel()">取 消</el-button>
        <el-button type="primary" @click="addRoleDialogCheck()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog :visible.sync="setRightsDialog" title="分配权限">
      <el-tree
        :data="rightsListTree"
        :props="rightsTreeProps"
        show-checkbox
        default-expand-all
        node-key="id"
        ref="rightsTreeRef"
        :default-checked-keys="checkedKeysArr"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialog = false">取 消</el-button>
        <el-button type="primary" @click="setRightsDiaComfirm()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getrolesForm()
  },
  data() {
    return {
      /* 角色信息表单 */
      roelsForm: [],
      /* 控制添加角色对话框显示隐藏 */
      addRoleDialog: false,
      /* 添加角色表单 */
      addRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      /* 添加角色表单验证规则 */
      addRoleRules: {
        roleName: [
          {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          },
          {
            max: 10,
            message: '长度不超过10个字符',
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            max: 10,
            message: '长度不超过10个字符',
            trigger: 'blur'
          }
        ]
      },
      /* 控制分配权限对话框显示隐藏 */
      setRightsDialog: false,
      /* 树形权限列表 */
      rightsListTree: [],
      /* 树形权限列表的props */
      rightsTreeProps: {
        children: 'children',
        label: 'authName'
      },
      /* 树形权限列表默认勾选id值数组 */
      checkedKeysArr: [],
      /* 即将分配权限的id */
      roleId: ''
    }
  },
  methods: {
    /* 获取角色信息 */
    async getrolesForm() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roelsForm = res.data
    },
    /* 添加角色对话框，点击确定操作 */
    addRoleDialogConfirm() {
      this.$refs.addRoleRef.validate(async valid => {
        if (!valid) {
          return
        }
        const { data: res } = await this.$http.post('roles', this.addRoleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加角色成功')
        this.getrolesForm()
        this.addRoleDialog = false
        this.$refs.addRoleRef.resetFields()
      })
    },
    /* 添加角色对话框，点击取消操作 */
    addRoleDialogCancel() {
      this.$message('已取消操作')
      this.addRoleDialog = false
      this.$refs.addRoleRef.resetFields()
    },
    /* 监听删除权限标签close事件 */
    async removeRightsClose(role, rightId) {
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败')
      }
      this.$message.success('删除权限成功')
      /* getrolesForm()重新获取数据, 导致roelsForm重新取得新的数据，页面从新渲染，体验不好 */
      /* 改变原数据 */
      role.children = res.data
    },
    /* 分配权限 */
    async setRightsShow(role) {
      this.roleId = role.id
      this.checkedKeysArr = []
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败')
      }
      this.rightsListTree = res.data
      this.getDefRightsById(role, 'id', this.checkedKeysArr)
      console.log(this.checkedKeysArr)
      this.setRightsDialog = true
    },
    /* 获得树形权限列表默认勾选的id值, 并保存到checkedKeysArr */
    getDefRightsById(node, idProp, defArr) {
      /* 如果当前node不包含children属性，则是三级节点 */
      if (!node.children) {
        return defArr.push(node[idProp])
      } else {
        node.children.forEach(item => {
          this.getDefRightsById(item, idProp, defArr)
        })
      }
    },
    /* 分配权限对话框，点击确定按钮 */
    async setRightsDiaComfirm() {
      const checkedKeys = [
        ...this.$refs.rightsTreeRef.getCheckedKeys(),
        ...this.$refs.rightsTreeRef.getHalfCheckedKeys()
      ]
      const checkedIdStr = checkedKeys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        {
          rids: checkedIdStr
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getrolesForm()
      this.setRightsDialog = false
    }
  }
}
</script>

<style lang="scss">
.el-breadcrumb {
  margin-bottom: 16px;
}
.el-breadcrumb__inner {
  font-size: 12px;
}
/* .el-card{
    box-shadow: 0, 0, 0, rgba(0, 0, 0, #ccc)
} */
.el-table {
  margin-top: 16px;
}
.el-row-top {
  border-top: solid 1px #eee;
}
.el-row-bottom {
  border-bottom: solid 1px #eee;
}
.el-tag {
  margin-top: 7px;
  margin-bottom: 7px;
}
.el-icon-caret-right {
  margin-left: 10px;
}
/* 垂直方向居中 */
.vcenter {
  display: flex;
  align-items: center;
}
</style>
